# coding: utf-8
# @Author: 莫小鱼
import random
import re
import time

from AutoApiTest.unit_tools.handle_data.yaml_handler import get_extract_yaml


class DebugTalk:

    def get_extratc_data(self, node_name, out_format=None):
        """
        获取extract.yaml数据，首先判断out_format是否为数字类型,如果不是则
        获取下一个节点的value
        :param node_name: extract.yaml的key值
        :param out_format: str类型，0：随机去读取，-1读取全部数据，返回字符串
                                -2：读取全部，返回列表格式，其他值：顺序读取
        :return:
        """
        data = get_extract_yaml(node_name)

        if out_format is not None and bool(re.compile(r'^[+-]?\d+$').match(str(out_format))):
            out_format = int(out_format)
            data_value = {
                out_format: self.seq_read(data, out_format),
                0: random.choice(data),
                -1: ','.join(data),
                -2: ','.join(data).split(',')
            }
            data = data_value[out_format]
        else:
            data = get_extract_yaml(node_name, out_format)
        return data

    @classmethod
    def seq_read(cls, data, out_format):
        """获取extract.yaml，第二个参数不为0，-1，-2的情况下"""
        if out_format not in [0, -1, -2]:
            return data[out_format - 1]
        else:
            return None

    @classmethod
    def params_md5(cls):
        pass

    @classmethod
    def get_now_time(cls):
        return time.time()

    @classmethod
    def get_headers(cls, params_type):
        """
        获取请求头
        :param params_type: 参数类型：如""data，"json"
        :return:
        """
        headers_mapping = {
            'data': {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
            'json': {'Content-Type': 'application/json;charset=UTF-8'}
        }
        headers = headers_mapping.get(params_type)
        if headers is None:
            raise ValueError('不支持其他类型的请求头设置')
        return headers


if __name__ == '__main__':
    debug = DebugTalk()
    res = debug.get_extratc_data('goodsId')
    print(res)
